package com.example.show_auto.data

import android.content.Context
import android.content.pm.PackageManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlinx.coroutines.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * 应用更新管理器
 */
class UpdateManager(private val context: Context) {
    
    // 更新API地址
    private val updateApiUrl = "http://1312361444-946bee144b.ap-guangzhou.tencentscf.com"
    
    // 设置存储
    private val settingsStorage = SettingsStorage(context)
    
    // 日期格式化器，用于比较日期
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    
    /**
     * 获取当前应用版本号
     */
    fun getCurrentVersion(): String {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionName ?: "1.0.0"
        } catch (e: PackageManager.NameNotFoundException) {
            "1.0.0"
        }
    }
    
    /**
     * 检查是否有可用更新
     */
    suspend fun checkForUpdate(): UpdateInfo {
        return withContext(Dispatchers.IO) {
            try {
                val currentVersion = getCurrentVersion()
                val url = URL("$updateApiUrl?current_version=$currentVersion")
                val connection = url.openConnection() as HttpURLConnection
                
                connection.apply {
                    requestMethod = "GET"
                    connectTimeout = 10000
                    readTimeout = 10000
                    setRequestProperty("User-Agent", "ShowAuto-Android/${currentVersion}")
                }
                
                val responseCode = connection.responseCode
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    val response = BufferedReader(InputStreamReader(connection.inputStream)).use { reader ->
                        reader.readText()
                    }
                    
                    val jsonObject = JSONObject(response)
                    UpdateInfo(
                        hasUpdate = jsonObject.getBoolean("hasUpdate"),
                        latestVersion = jsonObject.getString("latestVersion"),
                        currentVersion = jsonObject.getString("currentVersion"),
                        downloadUrl = jsonObject.getString("downloadUrl"),
                        updateMessage = jsonObject.getString("updateMessage"),
                        forceUpdate = jsonObject.getBoolean("forceUpdate"),
                        updateTime = jsonObject.getString("updateTime"),
                        releaseTitle = jsonObject.getString("releaseTitle")
                    )
                } else {
                    UpdateInfo(
                        hasUpdate = false,
                        latestVersion = currentVersion,
                        currentVersion = currentVersion,
                        downloadUrl = "",
                        updateMessage = "检查更新失败，请稍后重试",
                        forceUpdate = false,
                        updateTime = "",
                        releaseTitle = ""
                    )
                }
            } catch (e: Exception) {
                UpdateInfo(
                    hasUpdate = false,
                    latestVersion = getCurrentVersion(),
                    currentVersion = getCurrentVersion(),
                    downloadUrl = "",
                    updateMessage = "网络连接失败：${e.message}",
                    forceUpdate = false,
                    updateTime = "",
                    releaseTitle = ""
                )
            }
        }
    }
    
    /**
     * 检查是否需要自动检查更新
     * 逻辑：每天第一次启动应用时强制检查
     * 特殊情况：如果存在强制更新状态，每次启动都检查
     */
    fun shouldAutoCheck(): Boolean {
        // 如果存在强制更新状态，每次启动都需要检查
        if (settingsStorage.hasForceUpdatePending()) {
            return true
        }
        
        val lastCheckTime = settingsStorage.getLastCheckTime()
        val currentTime = System.currentTimeMillis()
        
        // 比较日期而不是时间间隔
        val lastCheckDate = dateFormat.format(Date(lastCheckTime))
        val currentDate = dateFormat.format(Date(currentTime))
        
        // 如果不是同一天，则表示今天还没检查过，需要检查
        return lastCheckDate != currentDate
    }
    
    /**
     * 自动检查更新（静默检查，不显示加载状态）
     */
    suspend fun autoCheckForUpdate(): UpdateInfo? {
        return try {
            if (!shouldAutoCheck()) {
                return null
            }
            
            val updateInfo = checkForUpdate()
            
            // 更新最后检查时间（非强制更新情况下）
            if (!updateInfo.forceUpdate) {
                settingsStorage.saveLastCheckTime(System.currentTimeMillis())
            }
            
            // 如果是强制更新，设置强制更新状态
            if (updateInfo.forceUpdate && updateInfo.hasUpdate) {
                settingsStorage.setForceUpdatePending(true)
                return updateInfo // 强制更新必须返回
            }
            
            // 只有在有更新时才返回结果
            if (updateInfo.hasUpdate) {
                updateInfo
            } else {
                null
            }
        } catch (e: Exception) {
            // 自动检查失败时静默处理
            null
        }
    }
}

/**
 * 更新信息数据类
 */
data class UpdateInfo(
    val hasUpdate: Boolean,
    val latestVersion: String,
    val currentVersion: String,
    val downloadUrl: String,
    val updateMessage: String,
    val forceUpdate: Boolean,
    val updateTime: String,
    val releaseTitle: String,
    val forceReason: String = "" // 强制更新原因
) 